<?php $not_tp_case = false;?>
<?php $bb_case = $this->inbound_warehouse_group_code=="BB";?>
<?php //$not_tp_case = $this->inbound_warehouse_group_code=="NVL" || $this->inbound_warehouse_group_code=="BB" ;?>

<script type="text/javascript">
<!--
	///khai báo
	var arr_invents = <?php echo Zend_Json::encode($this->array_inventorys) ;?>; //Json chua du lieu cua inventory, dang mang doi tuong [{}, {}...]
	var inventory_objects_arr = products = new Array; //Chuyen sang dang mang de dung cho autocomplete
	var inventory_objects_arr_oc = new Object; //Du lieu ho tro cho ham swapData
	
	<?php if ($not_tp_case) :?>
	var tps = <?php echo Zend_Json::encode($this->products) ;?>; //Json chua du lieu thanh pham, du lieu dang man []
	var tps_oc = new Object; //Convert tps to Objects
	if ( tps !=null ){
		for (var i = 0; i < tps.length; i++){
			tps_oc[tps[i]] = tps[i];
		}	
	}
	<?php endif ;?>
	
	if ( arr_invents != null ){
		for (var i = 0; i < arr_invents.length; i++){
			inventory_objects_arr.push({
				value: arr_invents[i].inventory_id,
				label: 
						arr_invents[i].inventory_product_code /*+ ' - ' +
						arr_invents[i].inventory_product_unit_code + ' - ' +
						arr_invents[i].inventory_quantity + ' - ' +
						arr_invents[i].location_name + ' - ' +
						arr_invents[i].inventory_product_time + ' - ' +
						arr_invents[i].inventory_expire_time + ' - ' +
						arr_invents[i].inventory_lot_code*/
				,
				focus_val: arr_invents[i].inventory_product_code
			});
			products[arr_invents[i].inventory_product_code] = arr_invents[i].product_name;
			inventory_objects_arr_oc[arr_invents[i].inventory_id] = arr_invents[i];
		}
	}
	
	var tmp_html = ''; //Bien luu tru giá tri tra ve khi goi ajax chon "Kho nhap hang"
	$(function(){
		//////////////////////
		//Xu ly tao phim tat// 
		//////////////////////
		$("#shortcut_button_insert").click(function(){
			$("#btn_add_new_product-top").trigger('click');
		});
		$("#shortcut_button_delete_all").click(function(){
			$("#btn_delete_all_product-top").trigger('click');
		});
		
		/////////////
		//jQuery UI//
		/////////////
		<?php /*if ($not_tp_case) :?>
		//tao autocomplete cho ma thanh pham, kiem tra du lieu nhap co dung?
		var chkSubPCodeExist = function(val){
			return ( val in tps_oc );
		};
		$("input.sub_product_code").live('focusin focusout', function(event){	
			if (event.type == 'focusin'){
				$(this).autocomplete({ source: tps });
			}else if (event.type == 'focusout'){
				$(this).val( $.trim( $(this).val() ) );
				
				if ( !chkSubPCodeExist( $(this).val() ) ){
					$(this).val('')	;
				}
			}
		});
		<?php endif ;*/?>
		
		//tao autocomplete cho ma san pham chinh, kiem tra du lieu nhap co dung?			
		var swapData = function(val, el){
			if (val in inventory_objects_arr_oc){
				var inventory = inventory_objects_arr_oc[val];
				var data = new Object;
				data.inbound_detail_product_code = inventory.inventory_product_code ;
				data.inbound_detail_product_unit_code = inventory.inventory_product_unit_code ;
				//data.inbound_detail_product_quantity = inventory.inventory_quantity ;
				//data.inbound_detail_location_code = inventory.inventory_location_code ;
				<?php /*if(!$bb_case){?>
				data.inbound_detail_product_time = inventory.inventory_product_time ;
				data.inbound_detail_expire_time = inventory.inventory_expire_time ;
				<?php }*/?>
				//data.inbound_detail_lot_code = inventory.inventory_lot_code ;
				//data.location_name = inventory.location_name ;								
				
				addProductToInboundDetail(data, $(el).closest('tr'));
			}		
		}			
		var chkProductCodeExist = function(val){
			return !( (products[val] == null) || typeof(products[val]) == 'undefined' );
		};			
		$("input.product_code").live('focusin focusout', function(event){
			var self = this;
			if (event.type == 'focusin'){
				$(this).autocomplete({
					source: inventory_objects_arr,					
					focus: function( event, ui ) {
						$(self).val( ui.item.focus_val );
						return false;
					},
					select: function( event, ui ) {
						//$(self).val( ui.item.value  );
						swapData(ui.item.value, self)
						return false;
					}					
				});
			}else if (event.type == 'focusout'){
				$(this).val( $.trim( $(this).val() ) );
				
				if ( !chkProductCodeExist( $(this).val() ) ){
					$(this).val('')	;
				}
			}
		});
		
		//xu lí cho phần chọn kho, các vị trí kho sẽ thay đổi theo	
		/*
		$('#inbound_warehouse_code').change(function(){			
			ajaxGetLocation();
		});
		*/
	
		//Xu ly them san pham vao chi tiet phieu nhap kho
		$("a[id^='btn_add_new_product']").click(function(){
			/*
			if ( $("#inbound_warehouse_code").val() == '' ){
				alert('Xin vui lòng xác định "KHO XUẤT HÀNG" trước.');
				$("#inbound_warehouse_code").focus();
			}else{*/
				addProductToInboundDetail();
			//}
			
		});
	
		//Xu ly xoa san pham khoi chi tiet phieu nhap kho.
			//Xoa tung san pham
		$("#table_inbound_detail tbody td.delete").live('click', function(){
			$(this).closest('tr').empty().detach();
			reCalculateNo();
		});
			//Xoa tat ca san pham
		$("a[id^='btn_delete_all_product']").click(function(){
			if (confirm('Bạn muốn xóa tất cả sản phẩm?')){
				$("#table_inbound_detail tbody").html('');
			}
		});	
	
		//Xu ly cho chon ly do
		$( "#inbound_reason_code" ).autocomplete({
			   change: function(event, ui) { 
				   $('#inbound_reason_code_2').val($('#inbound_reason_code').val());
					var use_company = $('#inbound_reason_code_2 option:selected').html();
					$('#inbound_company_code').css('display',use_company==1?'':'none');
					$('#inbound_company_code-label').css('display',use_company==1?'':'none');
					if($('#inbound_reason_code').val()!='')
						$('#inbound_note').val($('#inbound_reason_code').val().split(" - ")[1]);
			   }
			});
		
			//Giu lai gia tri nha cung cap
		$('#inbound_reason_code').trigger('change');
	
		////////////////////////////////////////////////////////////
		//MO PHONG - TAO LAI DU LIEU SAN PHAM TRONG PHIEU XUAT KHO//
		////////////////////////////////////////////////////////////
		<?php if (count((array)$this->inbound_details) > 0): ?>
		<?php
			foreach ($this->inbound_details as $key => $inbound_detail)
			{
				$location_name = $inbound_detail->m_Array['location_name'];
				$inbound_detail = $inbound_detail->toArray();
				if(!$bb_case)
				{	
					$inbound_detail['inbound_detail_product_time'] = $this->partial('index/format/time.phtml', 'admin', array($inbound_detail['inbound_detail_product_time']));
					$inbound_detail['inbound_detail_expire_time'] = $this->partial('index/format/time.phtml', 'admin', array($inbound_detail['inbound_detail_expire_time']));
				}
				$inbound_detail['location_name'] = $location_name;								
				$this->inbound_details[$key] = $inbound_detail;
			}
		?>
		
		var inbound_details = <?php echo Zend_Json::encode($this->inbound_details) ;?>;
		
			//Goi ajax cap nhat tao lai select VI TRI LUU KHO
		//ajaxGetLocation();
						
			//Tao lai san pham...
		for (var c = 0; c < inbound_details.length; c++){
			addProductToInboundDetail(inbound_details[c]);
		}
		
		<?php else: //lần đầu tiên, tạo trước 1 dòng?>

		//tạo 1 trước 1 sản phẩm
		addProductToInboundDetail();
			
		<?php endif; ?>		
		
	});
	//end.Document_Ready

	//Ham ho tro them san pham vao chi tiet phieu kho nhap kho.
	function addProductToInboundDetail(data, modified_tr){ 
		var not_modified = (modified_tr == null) || (typeof(modified_tr) == 'undefined');
		var new_tr = $("#table_partern tbody tr").eq(0).clone();	
		if( !not_modified ){ new_tr = modified_tr; }
		
		//Truong hop co do du lieu tro lai 		
		if (typeof(data) == 'object'){
			//Ham ho tro xu ly goi ajax lay gia tri select DON VI TINH
			$.ajax({
				type: "POST",
				url: "<?php echo $this->url(array("controller"=>"inbound-detail","action"=>"ajax-load-unit","module"=>"inbound"),null,true);?>",
				data: {"product_code":data.inbound_detail_product_code},
				async: false,
				success: function(html){
					$(new_tr).find('td.unit select').html(html);
				}
			});
			
			if(not_modified){ $(new_tr).find("input[name^='inbound_detail_sub_product_code']").val(data.inbound_detail_sub_product_code); } //Ma thanh pham
			$(new_tr).find("input[name^='inbound_detail_product_code']").val(data.inbound_detail_product_code); //Ma hang hoa
			$(new_tr).find('td.product_name').html( products[data.inbound_detail_product_code] ); //Ten hang hoa.
			$(new_tr).find("select[name^='inbound_detail_product_unit_code']").val(data.inbound_detail_product_unit_code); //Don vi tinh
			$(new_tr).find("input[name^='inbound_detail_product_quantity']").val(data.inbound_detail_product_quantity); //So luong
			//$(new_tr).find("select[name^='inbound_detail_location_code']").val(data.inbound_detail_location_code); //Vi tri luu kho
			$(new_tr).find("input[name^='inbound_detail_location_code']").val(data.inbound_detail_location_code); //Vi tri luu kho
			$(new_tr).find("input[name^='location_name']").val(data.location_name); //Vi tri luu kho
			$(new_tr).find("td.location span").html(data.location_name); //Vi tri luu kho
			<?php if(!$bb_case){?>
			$(new_tr).find("input[name^='inbound_detail_product_time']").val(data.inbound_detail_product_time); //Ngay san xuat
			$(new_tr).find("input[name^='inbound_detail_expire_time']").val(data.inbound_detail_expire_time); //Ngay het han
			<?php }?>
			$(new_tr).find("input[name^='inbound_detail_lot_code']").val(data.inbound_detail_lot_code); //Ma lot
			$(new_tr).find("input[name^='inbound_detail_note']").val(data.inbound_detail_note); //Ghi chu
		}
		
		if(not_modified){
			$("#table_inbound_detail tbody").append(new_tr);
			$(new_tr).find("input[name^='inbound_detail_product_code']").focus();
		}
		reCalculateNo();	
	}
	
	//Goi ham tinh lai stt cua tung dong trong bang inbound detail...
	function reCalculateNo(){
		var no = 0;
		$("#table_inbound_detail tbody tr").each(function(){
			$(this).find('td.no').html(++no);
		});
	}	
	
	//Ham ho tro xu ly goi ajax lay gia tri select VI TRI LUU KHO
	/*
	function ajaxGetLocation(){
		$.ajax({
			type: "POST",
			url: "<?php //echo $this->url(array("controller"=>"inbound-detail","action"=>"ajax-load-location","module"=>"inbound"),null,true);?>",
			data: {"location_warehouse_code":$('#inbound_warehouse_code').val()},
			async: false,
			success: function(html){
				tmp_html = html;
				for (var no = 0; no < $("#table_inbound_detail tbody tr").length; no++ ){
					$("#table_inbound_detail tbody tr").eq(no).find('td.location select').html(tmp_html);
				}
			}
		});			
	}
	*/

	//kiểm tra dữ liệu từng dòng
	function checkForm(){
		var error = false;
			//Xu ly kiem tra du lieu nhap vao...
		$("#adminForm .crequire").not(':hidden').not('[disabled]').each(function(){
			if ($(this).val() == ''){
				var label_text = $("label[for='"+ $(this).attr('id') +"']").text();
				alert('Xin vui lòng nhập dữ liệu cho "'+ label_text.toUpperCase() +'"');
				error = true;
				$(this).focus();
				return false;
			}
		});
		if (error) return false;
			
			//Phai co it nhat 1 san pham trong chi tiet phieu nhap...
		if ($("#table_inbound_detail tbody tr").length <= 0){
			alert("Xin vui lòng nhập sản phẩm.");
			return false;
		}else{
			var no = 1;
			var warehouse_group_name = '<?php echo $this->string_warehouse_group_name ?>';
			$("#table_inbound_detail tbody tr").each(function(){
				var msg_class = '';
				
				//Kiem tra du lieu ma san pham
				if ( $(this).find("input[name^='inbound_detail_product_code']").val() == '' ){
					var msg = 'Xin vui lòng nhập "MÃ '+ warehouse_group_name.toUpperCase() +'" ở dòng ' + no + '.';
					alert(msg);
					error = true;
					$(this).find("input[name^='inbound_detail_product_code']").focus();
					return false;
				}				
				
				//Kiem tra du lieu so luong
				if ( $(this).find("input[name^='inbound_detail_product_quantity']").val() == '' ){
					var msg = 'Xin vui lòng nhập "SỐ LƯỢNG" của sản phẩm nằm ở dòng ' + no + '.';
					alert(msg);
					error = true;
					$(this).find("input[name^='inbound_detail_product_quantity']").focus();
					return false;
				}				
				
				<?php /*if ($not_tp_case) :?>
				//Kiem tra du lieu nhap ma thanh pham
				if ( $(this).find("input[name^='inbound_detail_sub_product_code']").val() == '' ){
					var msg = 'Xin vui lòng nhập "MÃ THÀNH PHẨM" nằm ở dòng ' + no + '.';
					//system_messages(msg, msg_class);
					alert(msg);
					error = true;
					$(this).find("input[name^='inbound_detail_sub_product_code']").focus();
					return false;
				}
				<?php endif ;*/?>
				
				no++;
			});
		}
		if (!error){
			$("#adminForm").submit();
		} 
	}
			
</script>

<!-- thanh toolbar -->
<?php $this->placeholder('toolbar')->captureStart();?>
<?php //echo $this->partial('index/toolbar/save-and-close.phtml', 'admin', array("return checkForm()")) ?>
<?php echo $this->partial('index/toolbar/apply.phtml', 'admin', array("$('#adminAction').val('apply');return checkForm()")) ?>
<?php echo $this->partial('index/toolbar/save-and-new.phtml', 'admin', array("$('#adminAction').val('save-and-new'); return checkForm()")) ?>
<?php echo $this->partial('index/toolbar/divider.phtml', 'admin') ?>
<?php echo $this->partial('index/toolbar/cancel.phtml', 'admin') ?>
<?php $this->placeholder('toolbar')->captureEnd();?> 
<!-- / -->

<!-- nội dung form -->
<form method="post" action="" enctype="application/x-www-form-urlencoded" id="adminForm">
    <dl class="zend_form">
        <div class='col'>
            <fieldset id='fieldset_0'>
                <legend>Thông tin chung của phiếu</legend>
                <?php echo $this->form->inbound_id;?>
                <?php echo $this->form->adminAction;?>
                <?php echo $this->form->inbound_type;?>
                <?php echo $this->form->inbound_code;?>
                <?php echo $this->form->inbound_create_time?>
                <?php echo $this->form->inbound_create_user;?>
            </fieldset>
        </div>
        
        <div class='col'>
            <fieldset id='fieldset_1'>
                <legend>Thông tin xuất kho</legend>
				<?php echo $this->form->inbound_order_code;?>
                <?php //echo $this->form->inbound_warehouse_code;?>
                <?php //echo $this->form->inbound_warehouse_keep_user;?>
                <?php //echo $this->form->inbound_reason_code;?>	
                <?php //echo $this->form->inbound_reason_code_2->renderViewHelper();?>
                <?php echo $this->form->inbound_note;?>
            </fieldset>
            <fieldset id='fieldset_3'>
                <legend>Thông tin giao hàng</legend>
                <?php echo $this->form->inbound_company_code;?>
                <?php echo $this->form->inbound_delivery_user;?>				
            </fieldset>
        </div>
        
        <!-- THONG TIN CHI TIET -->  
        <?php $colspan=$not_tp_case?12:11;?>     
        <?php $colspan-=($bb_case?2:0);?>
        <div class='full'>
            <fieldset id='fieldset_2'>
                <legend>Thông tin chi tiết của phiếu xuất kho</legend>                    
                <table width="100%" border="0" cellspacing="0" cellpadding="5" class="adminlist" id="table_inbound_detail">
                    <thead>
                        <tr>
                            <td colspan="<?php echo $colspan?>" style="text-align:right;padding-bottom:10px">
								<input style="display:none" id="shortcut_button_insert" type="button" accesskey="Q" />
								<input style="display:none" id="shortcut_button_delete_all" type="button" accesskey="W" />
								<div class='bar'>
									<?php echo $this->partial('index/manage/button.phtml', 'admin', array('id'=>'btn_add_new_product-top', 'value'=>'Thêm một sản phẩm (Alt+Shift+Q)','class'=>'insert'));?>
									<?php echo $this->partial('index/manage/button.phtml', 'admin', array('id'=>'btn_delete_all_product-top', 'value'=>'Xóa tất cả sản phẩm (Alt+Shift+W)','class'=>'delete'));?>
								</div>
                            </td>
                        </tr>
                        <tr>
                            <th width='20px'>STT</th>                           	
                            <th width='70px'>Mã <?php //echo $this->inbound_warehouse_group_code ;?> <div class='require'></div></th>
                            <th>Tên <?php //echo $this->string_warehouse_group_name?></th>
                            <th width='90px'>ĐVT <div class='require'></div></th>
                            <th width='70px'>Số lượng <div class='require'></div></th>
                            <!-- <th width='110px'>Vị trí lưu kho</th> -->
                            <?php /*if(!$bb_case){?>
                            <th width='70px'>Ngày SX</th>
                            <th width='70px'>Ngày HH</th>
                           	<?php }*/?>
                            <!-- <th width='70px'>Mã lot</th> -->
                            <?php /*if ($not_tp_case): ?>
	                            <th width='90px'>Mã TP <div class="require"></div></th>
                            <?php endif ;*/?>
                            <th>Ghi chú</th>                            
                            <th width='30px'>Xóa</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td  colspan="<?php echo $colspan?>" style="text-align:right;padding-top:10px">
                                <div class='bar'>
									<?php echo $this->partial('index/manage/button.phtml', 'admin', array('id'=>'btn_add_new_product-top', 'value'=>'Thêm một sản phẩm (Alt+Shift+Q)','class'=>'insert'));?>
									<?php echo $this->partial('index/manage/button.phtml', 'admin', array('id'=>'btn_delete_all_product-top', 'value'=>'Xóa tất cả sản phẩm (Alt+Shift+W)','class'=>'delete'));?>
								</div>
                            </td>
                        </tr>
                    </tfoot>				
                </table>
                <!-- end.THONG TIN CHI TIET -->
            </fieldset>
        </div>
    </dl>
</form>
<table id="table_partern">
    <tbody>
        <tr>
            <td class="center no"></td>            
            <td><input class="product_code" type="text" name="inbound_detail_product_code[]" /></td>
            <td class="product_name"></td>
            <td class='unit'>
                <select name="inbound_detail_product_unit_code[]">
					<option value="">- Chọn -</option>
	                <?php foreach($this->units as $unit) : ?>
	                    <option value="<?php echo $unit->unit_code ?>"><?php echo $unit->unit_name; ?></option>
	                <?php endforeach;?>
                </select>
            </td>
            <td><input type="text" name="inbound_detail_product_quantity[]" class="numeric" /></td>
            <!-- <td class="location">
				<input type="hidden" name="inbound_detail_location_code[]" value="" />
				<input type="hidden" name="location_name[]" value="" />
				<span></span>
			</td> -->
			<?php /*if(!$bb_case){?>
            <td><input class="datepicker lock time" name="inbound_detail_product_time[]" type="text" /></td>
            <td><input class="datepicker lock time" name="inbound_detail_expire_time[]" type="text" /></td>
            <?php }*/?>
            <!-- <td><input class="lock" name="inbound_detail_lot_code[]" type="text" /></td> -->
            <?php /*if ($not_tp_case): ?>
	            <td><input class="sub_product_code" type="text" name="inbound_detail_sub_product_code[]" /></td>
            <?php endif ;*/?>
            <td><input name="inbound_detail_note[]" type="text" /></td>
            <td class="center delete"><?php echo $this->partial('index/manage/icon.phtml', 'admin', array('class'=>'icon-16-trash', 'href'=>'javascript:void(0)'));?></td>
        </tr>
    </tbody>
</table>
<!-- / -->